package com.easylinkin.linkappapi.listener;

import com.alibaba.fastjson.JSON;
import com.easylinkin.linkappapi.investigation.entity.InvestigationTaskDetail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * <p> 隐患排查监控页面的监听</p>
 */
@ServerEndpoint("/investigationTaskDetailListener/{investigationTaskDetailId}/{handleUserId}")
@Component
public class InvestigationTaskDetailListener extends Listener {

    private static final Logger LOGGER = LoggerFactory.getLogger(InvestigationBigScreenListener.class);

    private static CopyOnWriteArraySet<Listener> webSocketSet = new CopyOnWriteArraySet<>();


    @Override
    @OnOpen
    public void onOpen(Session session, @PathParam("investigationTaskDetailId") String investigationTaskDetailId, @PathParam("handleUserId") String handleUserId) {
        LOGGER.info("session.getRequestURI():" + session.getRequestURI());
        init(session, investigationTaskDetailId, handleUserId);
        // 加入set中
        webSocketSet.add(this);
    }

    /**
     * 连接关闭调用的方法
     */
    @Override
    @OnClose
    public void onClose() {
        LOGGER.info("通知关闭连接,用户id:{}", getUserId());
        // 从set中删除
        webSocketSet.remove(this);
    }

    /***
     * 消息推送
     * @param investigationTaskDetail 排查详情
     */
    public void sendNotice(InvestigationTaskDetail investigationTaskDetail) {
        String jsonText = JSON.toJSONString(investigationTaskDetail);
        for (Listener listener : webSocketSet) {
            if (listener.getUserId() != null && listener.getUserId().equals(investigationTaskDetail.getUserId())) {
                listener.sendMessage(jsonText);
            }
        }
    }

}
